package cn.learn.service.system.role.impl;

import cn.learn.dao.system.role.RoleDao;
import cn.learn.domain.system.role.Role;
import cn.learn.service.system.role.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    /**
     * 分页查询全部角色方法
     * @param pageNum
     * @param PageSize
     * @return
     */
    @Override
    public PageInfo selectAllByPage(int pageNum, int PageSize, String companyId) {
        PageHelper.startPage(pageNum, PageSize);
        List<Role> resultRole =  roleDao.selectAll(companyId);
        PageInfo resultData = new PageInfo(resultRole);
        return resultData;
    }

    /**
     * 添加一条角色
     * @param role
     */
    @Override
    public void addOne(Role role) {
        roleDao.addOne(role);
    }

    /**
     * 根据id查询一条数据
     * @param role
     * @return
     */
    @Override
    public Role findOneById(Role role) {
        Role resultRole = roleDao.findOneById(role);
        return resultRole;
    }

    /**
     * 根据id修改一条数据
     * @param role
     */
    @Override
    public void updateOneById(Role role) {
        roleDao.updateOneById(role);
    }

    /**
     * 根据id删除一条数据
     * @param id
     */
    @Override
    public void deleteOneById(String id) {
        roleDao.deleteOneById(id);
    }

    /**
     * 修改用户所有权限
     * @param roleId
     * @param moduleIds
     */
    @Override
    public void updateRoleModules(String roleId, String moduleIds) {
        // 删除原有权限
        roleDao.deleteRoleModuleById(roleId);
        // 添加新权限
        String[] ids = moduleIds.split(",");
        for (String id : ids) {
            roleDao.addRoleModule(roleId, id);
        }
    }

    /**
     * 查询企业所有角色
     * @param companyId
     * @return
     */
    @Override
    public List<Role> selectAll(String companyId) {
        List<Role> resultRole = roleDao.selectAll(companyId);
        return resultRole;
    }

    /**
     * 查询用户所拥有的角色
     * @param id
     * @return
     */
    @Override
    public List<Role> selectUserRole(String id) {
        List<Role> userRole = roleDao.selectUserRole(id);
        return userRole;
    }

    /**
     * 修改用户拥有的权限
     * @param userId
     * @param roleIds
     */
    @Override
    public void updateUserRole(String userId, String[] roleIds) {
        roleDao.deleteUserRoleById(userId);
        for (String roleId : roleIds) {
            roleDao.addOneUserRole(userId, roleId);
        }
    }
}
